package com.example.demo.common;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode; 
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.CharsetUtils;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Entity;

import com.alibaba.fastjson.JSONObject;

//描述：HTTP 请求模块
//时间：2019-05-17
public class HttpUtils {

	public static boolean StringIsNullOrEmpty(String value) {
		if(value!=null && value !="") {
			return false;
		}
		return true;
	}
	
	/**
	 * 
	 * @param url
	 * @param contentType
	 * @param data
	 * @return
	 * @throws IOException
	 */
	public static String Post(String url,String contentType, String data) throws IOException {
		
		String responseString="";
		
		CloseableHttpClient httpclient = HttpClients.createDefault();

		try {

			HttpPost request = new HttpPost(url);
			
//			配置信息可选配置超时时间等
//			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(6000).setConnectTimeout(6000).build();//设置请求和传输超时时间
//			request.setConfig(requestConfig);			
			
			//UrlEncodeFormEntity会将参数以key1=value1&key2=value2的键值对形式发出。类似于传统的application/x-www-form-urlencoded表单上传
			//StringEntity可以自己指定ContentType，而默认值是 text/plain，数据的形式就非常自由了，可以组织成自己想要的任何形式，一般用来存储json数据
			//MultipartEntity文件上传用到，类似于表单的类型为multipart/form-data
			
			StringEntity reqEntity = new StringEntity(data,StandardCharsets.UTF_8); //StandardCharsets.UTF_8
			if(!StringIsNullOrEmpty(contentType))
			{
				//"application/x-www-form-urlencoded"
				reqEntity.setContentType(contentType);
			}			 
			request.setEntity(reqEntity);
			
//			List<NameValuePair> formparams=new ArrayList<NameValuePair>();
//	        formparams.add(new BasicNameValuePair("name","adfasdfasdfs"));	         
//			HttpEntity reqEntity=new UrlEncodedFormEntity(formparams,"utf-8");
 
//			System.out.println(reqEntity.toString());
//			request.setEntity(reqEntity);			

			//HttpResponse httpResponse = httpclient.execute(request); 
			CloseableHttpResponse response = httpclient.execute(request); 
		    
		    //获取响应实体  
		    HttpEntity entity = response.getEntity();
		    
		    responseString = EntityUtils.toString(entity,StandardCharsets.UTF_8);			
		    response.close();
		    
		}
		catch (Exception e) {
			// TODO: handle exception
			responseString=e.getMessage();			
		}
		
	    httpclient.close();	    
		return responseString;
		
	}
	
	/**
	 * 
	 */
	public static String Get(String url) throws IOException {
		 
		String responseString="";
		
		CloseableHttpClient httpclient = HttpClients.createDefault();  
		
		 try {
			 // 创建httpget.    
	         HttpGet request = new HttpGet(url); 
	         
	         //HttpResponse response = httpclient.execute(request); 	         
	         CloseableHttpResponse response = httpclient.execute(request);  
	         
	         //获取响应实体    
             HttpEntity entity = response.getEntity();               
             responseString = EntityUtils.toString(entity,StandardCharsets.UTF_8);
	         
             response.close();             
		 }
		 catch (Exception e) {			
			 // TODO: handle exception
			 responseString=e.getMessage();			 
		 }
		 
		 httpclient.close();		 
		 return responseString;
		 
	}
	
	/**
	 * 
	 * @param url
	 * @param values
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String Post(String url, HashMap<String, Object> values) throws UnsupportedEncodingException {
		
		String responseString="";
		
		CloseableHttpClient httpclient = HttpClients.createDefault();
		
		try {
			
			HttpPost request = new HttpPost(url);
			
			//使用浏览器兼容模式，并且设置编码，防止文件名乱码问题
	        MultipartEntityBuilder builder = MultipartEntityBuilder.create()
	                .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
	                .setCharset(CharsetUtils.get("UTF-8")); //编码  
	        
//	        FileBody fileBody=new FileBody(new File("d://123.txt"));
//	        builder.addPart("file", fileBody);      
//	        builder.addTextBody("name", "123.txt");
	        
	        for (Entry<String,Object> entity : values.entrySet()) {
	        	 Object valueObject=entity.getValue();
	        	 if(valueObject.getClass()==FileBody.class) {
	        		 builder.addPart(entity.getKey(), (FileBody)entity.getValue());
	        	 }
	        	 else {
	        		 builder.addTextBody(entity.getKey(), (String)entity.getValue());
	        	 }				
			}

	        HttpEntity reqEntity=builder.build();	
	        
	        request.setEntity(reqEntity);
	        
            CloseableHttpResponse response = httpclient.execute(request); 
		    
		    //获取响应实体  
		    HttpEntity entity = response.getEntity();
		    
		    responseString = EntityUtils.toString(entity,StandardCharsets.UTF_8);			
		    response.close();	        
	        
		}
		catch (Exception e) {
			// TODO: handle exception
			responseString=e.getMessage();
		}
        
        return responseString;
	}
	
	
}
